<template>
  <div class="daily-statistics-container">
    <div class="page-header">
      <h2 class="page-title">日常统计</h2>
      <div class="header-actions">
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
        <el-button type="primary" @click="exportExcel">
          <el-icon><Download /></el-icon>导出Excel
        </el-button>
      </div>
    </div>
    
    <!-- 日期选择器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="统计日期">
          <el-date-picker
            v-model="filterForm.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disableFutureDate"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select v-model="filterForm.businessTypeId" placeholder="请选择业务类型" clearable @change="handleFilterChange">
            <el-option label="全部" :value="null" />
            <el-option 
              v-for="item in businessTypes" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="窗口">
          <el-select v-model="filterForm.windowId" placeholder="请选择窗口" clearable @change="handleFilterChange">
            <el-option label="全部" :value="null" />
            <el-option 
              v-for="item in windows" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="statistic-card total-card">
            <div class="card-content">
              <div class="card-icon">
                <el-icon><Ticket /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ summaryData.totalTickets }}</div>
                <div class="card-label">总取号数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="statistic-card finished-card">
            <div class="card-content">
              <div class="card-icon">
                <el-icon><Check /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ summaryData.finishedTickets }}</div>
                <div class="card-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="statistic-card waiting-card">
            <div class="card-content">
              <div class="card-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ summaryData.waitingTickets }}</div>
                <div class="card-label">等待中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="statistic-card abandoned-card">
            <div class="card-content">
              <div class="card-icon">
                <el-icon><CloseBold /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ summaryData.abandonedTickets }}</div>
                <div class="card-label">已放弃</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 图表和详细数据 -->
    <div class="data-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>业务类型分布</span>
              </div>
            </template>
            <div id="business-type-chart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>时段分布</span>
              </div>
            </template>
            <div id="hourly-chart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 详细数据表格 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>详细数据</span>
        </div>
      </template>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="time" label="时间段" width="120" />
        <el-table-column prop="businessType" label="业务类型" width="150" />
        <el-table-column prop="window" label="窗口" width="150" />
        <el-table-column prop="totalTickets" label="取号数" width="100" />
        <el-table-column prop="finishedTickets" label="完成数" width="100" />
        <el-table-column prop="abandonedTickets" label="放弃数" width="100" />
        <el-table-column prop="avgWaitTime" label="平均等待时间(分钟)" width="180" />
        <el-table-column prop="avgProcessTime" label="平均处理时间(分钟)" min-width="180" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { Refresh, Download, Ticket, Check, Timer, CloseBold } from '@element-plus/icons-vue'

export default {
  name: 'DailyStatistics',
  components: {
    Refresh,
    Download,
    Ticket,
    Check,
    Timer,
    CloseBold
  },
  setup() {
    // 图表实例
    let businessTypeChart = null
    let hourlyChart = null
    
    // 基础数据
    const loading = ref(false)
    const filterForm = reactive({
      date: new Date().toISOString().slice(0, 10), // 默认今天
      businessTypeId: null,
      windowId: null
    })
    
    // 模拟业务类型数据
    const businessTypes = [
      { id: 1, name: '普通业务', code: 'A' },
      { id: 2, name: '特殊业务', code: 'B' },
      { id: 3, name: '紧急业务', code: 'C' },
      { id: 4, name: '企业业务', code: 'D' },
      { id: 5, name: '临时业务', code: 'E' }
    ]
    
    // 模拟窗口数据
    const windows = [
      { id: 1, name: '综合服务窗口1', number: '01' },
      { id: 2, name: '综合服务窗口2', number: '02' },
      { id: 3, name: '企业服务窗口', number: '03' },
      { id: 4, name: '应急窗口', number: '04' }
    ]
    
    // 模拟统计数据
    const generateMockData = () => {
      // 模拟汇总数据
      const summaryData = {
        totalTickets: Math.floor(Math.random() * 200) + 100,
        finishedTickets: 0,
        waitingTickets: 0,
        abandonedTickets: 0
      }
      
      // 计算已完成和放弃的，确保总数一致
      summaryData.finishedTickets = Math.floor(summaryData.totalTickets * (0.7 + Math.random() * 0.2))
      summaryData.abandonedTickets = Math.floor((summaryData.totalTickets - summaryData.finishedTickets) * 0.8)
      summaryData.waitingTickets = summaryData.totalTickets - summaryData.finishedTickets - summaryData.abandonedTickets
      
      // 生成业务类型分布数据
      const businessTypeData = businessTypes.map(type => {
        const value = Math.floor(Math.random() * 50) + 10
        return { name: type.name, value }
      })
      
      // 生成时段分布数据
      const hourlyData = {
        times: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00'],
        values: []
      }
      
      hourlyData.values = hourlyData.times.map(() => Math.floor(Math.random() * 30) + 5)
      
      // 生成详细表格数据
      const tableData = []
      
      // 为每个时间段生成数据
      hourlyData.times.forEach(time => {
        // 为每个业务类型生成数据
        businessTypes.forEach(type => {
          // 为每个窗口生成一些数据
          windows.forEach(window => {
            // 只生成一部分组合，使数据更真实
            if (Math.random() > 0.7) return
            
            const totalTickets = Math.floor(Math.random() * 20) + 1
            const finishedTickets = Math.floor(totalTickets * (0.6 + Math.random() * 0.4))
            const abandonedTickets = Math.floor((totalTickets - finishedTickets) * Math.random())
            
            tableData.push({
              time,
              businessType: type.name,
              businessTypeId: type.id,
              window: window.name,
              windowId: window.id,
              totalTickets,
              finishedTickets,
              abandonedTickets,
              avgWaitTime: (Math.random() * 10 + 5).toFixed(1),
              avgProcessTime: (Math.random() * 15 + 3).toFixed(1)
            })
          })
        })
      })
      
      return {
        summaryData,
        businessTypeData,
        hourlyData,
        tableData
      }
    }
    
    // 初始化数据
    const mockData = generateMockData()
    const summaryData = reactive(mockData.summaryData)
    const businessTypeData = ref(mockData.businessTypeData)
    const hourlyData = ref(mockData.hourlyData)
    const fullTableData = ref(mockData.tableData)
    
    // 分页相关
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: mockData.tableData.length
    })
    
    // 根据筛选条件和分页获取表格数据
    const tableData = computed(() => {
      // 应用筛选条件
      let filteredData = fullTableData.value.filter(item => {
        let businessTypeMatch = true
        let windowMatch = true
        
        if (filterForm.businessTypeId !== null) {
          businessTypeMatch = item.businessTypeId === filterForm.businessTypeId
        }
        
        if (filterForm.windowId !== null) {
          windowMatch = item.windowId === filterForm.windowId
        }
        
        return businessTypeMatch && windowMatch
      })
      
      // 注意：这里不应该在计算属性中修改外部状态
      // 返回分页数据
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      
      return filteredData.slice(start, end)
    })
    
    // 添加一个监听器来更新分页总数
    watch([() => filterForm.businessTypeId, () => filterForm.windowId], () => {
      const filteredData = fullTableData.value.filter(item => {
        let businessTypeMatch = true
        let windowMatch = true
        
        if (filterForm.businessTypeId !== null) {
          businessTypeMatch = item.businessTypeId === filterForm.businessTypeId
        }
        
        if (filterForm.windowId !== null) {
          windowMatch = item.windowId === filterForm.windowId
        }
        
        return businessTypeMatch && windowMatch
      })
      
      // 更新总数
      pagination.total = filteredData.length
      pagination.currentPage = 1
    })
    
    // 初始化图表
    const initCharts = () => {
      // 业务类型分布图
      businessTypeChart = echarts.init(document.getElementById('business-type-chart'))
      const businessTypeOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          data: businessTypeData.value.map(item => item.name)
        },
        series: [
          {
            name: '业务类型分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: businessTypeData.value
          }
        ]
      }
      businessTypeChart.setOption(businessTypeOption)
      
      // 时段分布图
      hourlyChart = echarts.init(document.getElementById('hourly-chart'))
      const hourlyOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: hourlyData.value.times,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '取号数',
            type: 'bar',
            barWidth: '60%',
            data: hourlyData.value.values,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      }
      hourlyChart.setOption(hourlyOption)
      
      // 窗口大小变化时重绘图表
      window.addEventListener('resize', () => {
        businessTypeChart.resize()
        hourlyChart.resize()
      })
    }
    
    // 禁用未来日期
    const disableFutureDate = (time) => {
      return time.getTime() > Date.now()
    }
    
    // 处理日期变化
    const handleDateChange = () => {
      refreshData()
    }
    
    // 处理筛选条件变化
    const handleFilterChange = () => {
      pagination.currentPage = 1
      updateSummaryData()
      updateChartData()
    }
    
    // 更新汇总数据
    const updateSummaryData = () => {
      // 根据筛选条件汇总数据
      let totalTickets = 0
      let finishedTickets = 0
      let abandonedTickets = 0
      
      const filteredData = fullTableData.value.filter(item => {
        let businessTypeMatch = true
        let windowMatch = true
        
        if (filterForm.businessTypeId !== null) {
          businessTypeMatch = item.businessTypeId === filterForm.businessTypeId
        }
        
        if (filterForm.windowId !== null) {
          windowMatch = item.windowId === filterForm.windowId
        }
        
        return businessTypeMatch && windowMatch
      })
      
      filteredData.forEach(item => {
        totalTickets += item.totalTickets
        finishedTickets += item.finishedTickets
        abandonedTickets += item.abandonedTickets
      })
      
      // 更新汇总数据
      summaryData.totalTickets = totalTickets
      summaryData.finishedTickets = finishedTickets
      summaryData.abandonedTickets = abandonedTickets
      summaryData.waitingTickets = totalTickets - finishedTickets - abandonedTickets
    }
    
    // 更新图表数据
    const updateChartData = () => {
      // 根据筛选条件更新图表数据
      const filteredData = fullTableData.value.filter(item => {
        let businessTypeMatch = true
        let windowMatch = true
        
        if (filterForm.businessTypeId !== null) {
          businessTypeMatch = item.businessTypeId === filterForm.businessTypeId
        }
        
        if (filterForm.windowId !== null) {
          windowMatch = item.windowId === filterForm.windowId
        }
        
        return businessTypeMatch && windowMatch
      })
      
      // 更新业务类型图表
      if (filterForm.businessTypeId === null) {
        // 按业务类型统计数据
        const businessTypeStats = {}
        
        filteredData.forEach(item => {
          if (!businessTypeStats[item.businessType]) {
            businessTypeStats[item.businessType] = 0
          }
          businessTypeStats[item.businessType] += item.totalTickets
        })
        
        const newBusinessTypeData = Object.keys(businessTypeStats).map(name => {
          return { name, value: businessTypeStats[name] }
        })
        
        businessTypeData.value = newBusinessTypeData
        
        const businessTypeOption = {
          legend: {
            data: newBusinessTypeData.map(item => item.name)
          },
          series: [
            {
              data: newBusinessTypeData
            }
          ]
        }
        
        businessTypeChart.setOption(businessTypeOption)
      }
      
      // 更新时段图表
      const hourlyStats = {}
      hourlyData.value.times.forEach(time => {
        hourlyStats[time] = 0
      })
      
      filteredData.forEach(item => {
        if (hourlyStats[item.time] !== undefined) {
          hourlyStats[item.time] += item.totalTickets
        }
      })
      
      const newHourlyValues = hourlyData.value.times.map(time => hourlyStats[time])
      
      const hourlyOption = {
        series: [
          {
            data: newHourlyValues
          }
        ]
      }
      
      hourlyChart.setOption(hourlyOption)
    }
    
    // 刷新数据
    const refreshData = () => {
      loading.value = true
      
      // 模拟加载
      setTimeout(() => {
        // 生成新的模拟数据
        const newData = generateMockData()
        
        // 更新数据
        Object.assign(summaryData, newData.summaryData)
        businessTypeData.value = newData.businessTypeData
        hourlyData.value = newData.hourlyData
        fullTableData.value = newData.tableData
        
        // 重新应用筛选条件
        updateSummaryData()
        updateChartData()
        
        loading.value = false
        ElMessage.success('数据已刷新')
      }, 800)
    }
    
    // 导出Excel
    const exportExcel = () => {
      ElMessage.success('数据已导出到Excel文件')
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }
    
    // 组件挂载后初始化图表
    onMounted(() => {
      initCharts()
    })
    
    return {
      loading,
      filterForm,
      businessTypes,
      windows,
      summaryData,
      tableData,
      pagination,
      disableFutureDate,
      handleDateChange,
      handleFilterChange,
      refreshData,
      exportExcel,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.daily-statistics-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.statistics-cards {
  margin-bottom: 20px;
}

.statistic-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 16px;
}

.card-icon .el-icon {
  font-size: 30px;
  color: #fff;
}

.card-info {
  display: flex;
  flex-direction: column;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.total-card .card-icon {
  background-color: #409EFF;
}

.finished-card .card-icon {
  background-color: #67C23A;
}

.waiting-card .card-icon {
  background-color: #E6A23C;
}

.abandoned-card .card-icon {
  background-color: #F56C6C;
}

.data-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>